package com.study.kafkademo01.service.impl;

import com.study.kafkademo01.service.KafkaConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * @author weixiaochun
 */
@Service
@Slf4j
public class KafkaConsumerServiceImpl implements KafkaConsumerService {


    @Override
    public void getMessage() {
        //1、创建消费者配置
        Properties properties = new Properties();
        //链接的集群
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.56.20:9092,192.168.56.30:9092");
        //开启自动提交
//        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        //自动提交offset 偏移量，延时默认为1000ms
//        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
        //Key、Value的反序列化类
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        //消费组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "testData");
        //重置消费者的offset
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");


        //2、创建消费者
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

        //3、订阅主题
        consumer.subscribe(Collections.singleton("first"));



        while(true){
            //Kafka是维护了一个长轮询，如果没有内容，会睡眠100ms，等待下一次拉取
            //获取数据
            ConsumerRecords<String, String> records = consumer.poll(100);

            //解析并打印consumerRecords
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(record.key() + "-----" + record.value());
            }

            //异步提交
            consumer.commitAsync((offsets, exception) -> {
                log.error("offsets：" + offsets);
                if(exception != null){
                    log.info("提交offset错误");
                    log.info("offsets：" + offsets);
                }
            });
        }
    }
}
